const fs = require('fs');
const OSS = require('ali-oss');
const client = new OSS({
  accessKeyId: 'Ve2yhH1AdH5OdRDM',
  accessKeySecret: 'aoXEiRNJ3xf1xNbI9xCPy29iQPXdNv',
  bucket: 'dims2',
  region: 'oss-cn-hangzhou'
});

// UUID
const uuidv4 = require('uuid/v4');
// uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a'
const getObjectName = ()=> uuidv4().replace(/-/g, '');


// 上传
async function upload(path){
  try {
    // use 'chunked encoding'
    let stream = fs.createReadStream(path);
    let object_name = getObjectName();
    let result = await client.putStream(object_name, stream);
    // console.log(result);
    return result;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  }
}

// 下载, 得到文件流
async function download(object_name){
  if(!object_name){
    throw new Error('请给出dims2 桶下文件对象的名字object name');
  }
  let result = await client.get(object_name);
  // console.log(result.content);
  // return url;
  return result.content;
}

// 下载，得到文件url
function getFileUrl(object_name){
  let url = client.signatureUrl(object_name);
  return url;
}

module.exports = {upload, download};
